package ru.urfc.portal.managers;

import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

import ru.urfc.portal.dao.RadioDao;
import ru.urfc.portal.dao.SpectrId;
import ru.urfc.portal.model.SpectrObject;
import ru.urfc.portal.model.radio.Device;
import ru.urfc.portal.model.radio.NetFrequencyAssignment;
import ru.urfc.portal.model.radio.NetLicense;
import ru.urfc.portal.model.radio.NetWithDevicesNumber;
import ru.urfc.portal.model.radio.NetWithLicense;

@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class NetManager extends BaseManager {

	@EJB RadioDao radioDao;

	public List<NetWithDevicesNumber> getNets(Long clientId) {
		return radioDao.getNets(getClient(clientId), new Date());
	}

	private NetWithLicense getNet(Long clientId, Long netId) {
		final NetWithLicense net = get(NetWithLicense.class, clientId, netId);
		net.setRegion(getClient(clientId).getBranch().getRegion());
		return net;
	}

	public NetWithLicense getNetWithLicense(Long clientId, Long netId) {
		SpectrId contragentId = getContragentId(clientId);
		NetWithLicense net = getNet(clientId, netId);
		NetLicense currentLicense = radioDao.getNetCurrentLicense(
				new SpectrId(net.getId(), contragentId), new Date());
		net.setCurrentLicense(currentLicense);
		return net;
	}

	protected <T extends SpectrObject> List<T> getNetDescendants(Class<T> descendantClass, Long clientId, Long netId) {
		SpectrId contragentId = getContragentId(clientId);
		getNet(clientId, netId); // check
		return find(contragentId.getBranch(), descendantClass, "net.id", netId);
	}
	
	public List<NetFrequencyAssignment> getNetChannels(Long clientId, Long netId) {
		return getNetDescendants(NetFrequencyAssignment.class, clientId, netId);
	}

	public List<Device> getNetDevices(Long clientId, Long netId) {
		return getNetDescendants(Device.class, clientId, netId);
	}

	public List<NetLicense> getNetLicenses(Long clientId, Long netId) {
		return getNetDescendants(NetLicense.class, clientId, netId);
	}

	public NetLicense getNetLicense(Long clientId, Long netId, Long licenseId) {
		getNet(clientId, netId); // check
		return findById(NetLicense.class, new SpectrId(licenseId, getContragentId(clientId))).check(netId);
	}
	
}
